import * as path from "path";
import * as fs from 'fs';
import * as fse from 'fs-extra';

/**
 * 判断字符串是否匹配其中的正则
 * @param fileFormatList 正则列表
 * @param str 字符串
 */
export function checkIsMatch(fileFormatList: RegExp[], str: string) {
  for (let i = 0; i < fileFormatList.length; i++) {
    const regExp = fileFormatList[i];
    if (regExp.test(str)) return true;
  }
  return false;
}

/**
 * 找到目录下所有匹配的文件
 * @param typesDir 目录
 * @param fileFormatList 文件正则列表
 * @returns 符合要求的文件路径
 */
export async function findFiles(typesDir: string, fileFormatList: Array<RegExp>) {
  const fileList: string[] = [];
  const files = await fse.readdir(typesDir);
  for (let i = 0; i < files.length; i++) {
    const fileName = files[i];
    const dir = path.resolve(typesDir, fileName);
    if (fs.statSync(dir).isDirectory()) {
      fileList.push(...await findFiles(dir, fileFormatList));
    }
  }
  fileList.push(...files.filter(file => checkIsMatch(fileFormatList, file)).map(filename => path.resolve(typesDir, filename)));
  return fileList;
}


/**
 * dto类命名转换
 */
export function dtoNameTransfer(className: string) {
  if (className.endsWith('Dto')) {
    return className.slice(0, className.length - 3) + 'Zod';
  } else if (className.endsWith('Vo')) {
    return className + 'Zod';
  }
  return className;
}
